<?php

/**
 * 资讯类
 */
class medalModel
{


    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    /**
     * 创建勋章redis
     * @return array
     */
    public function creteMedalRedis()
    {
        $this->redis->del(REDIS_PREFIX.'SMedalList');
        $this->redis->del(REDIS_PREFIX.'CMedalList');
        $data = $this->db->getall("select * from r_medal order by medal_id ASC");
        foreach ($data as $info) {
            $medal_id = $info['medal_id'];
            $this->redis->del(REDIS_PREFIX.'SMedalInfo_'.$medal_id);
            $this->redis->del(REDIS_PREFIX.'CMedalInfo_'.$medal_id);
            if($info['isCustom'] == 0 || $info['isCustom'] == 2)
            {
                $this->redis->sadd(REDIS_PREFIX.'SMedalList', $medal_id);
                unset($info['start_time'], $info['end_time'], $info['mileage_limit']);
                // 删除redis数据后再新建
                $this->redis->hmset(REDIS_PREFIX.'SMedalInfo_'.$medal_id, $info);
            }
            else
            {
                $this->redis->zadd(REDIS_PREFIX.'CMedalList', $medal_id, $medal_id);
                $this->redis->hmset(REDIS_PREFIX.'CMedalInfo_'.$medal_id, $info);
            }
        }
        exit(date("Y-m-d H:i:s"));
    }
    /**
     * 勋章详情
     * @return array
     */
    public function getMedalInfo($medal_id)
    {
        $medalInfo = array();
        $is_custom = $this->redis->sismember(REDIS_PREFIX.'SMedalList', $medal_id) ? 0 : 1;
        if($is_custom)
        {
            $medalInfo = $this->redis->hgetall(REDIS_PREFIX.'CMedalInfo_'.$medal_id);
            if(empty($medalInfo))
            {
                $medalInfo = $this->db->getRowTable('r_medal', array(),"medal_id = '{$medal_id}'");
                $medalInfo && $this->redis->hmset(REDIS_PREFIX.'CMedalInfo_'.$medal_id, $medalInfo);
            }
        }
        else
        {
            $medalInfo = $this->redis->hgetall(REDIS_PREFIX.'SMedalInfo_'.$medal_id);
            if(empty($medalInfo))
            {
                $medalInfo = $this->db->getRowTable('r_medal', array(), "medal_id = '{$medal_id}'");
                $this->redis->hmset(REDIS_PREFIX.'SMedalInfo_'.$medal_id, $medalInfo);
            }
        }
        if(!empty($medalInfo)){
            !isset($medalInfo['cate']) && $medalInfo['cate'] = 1;
            !isset($medalInfo['gender']) && $medalInfo['gender'] = 0;
        }
        return $medalInfo;
    }

    /**
     * 获取新的自定义勋章
     * @return array
     */
    public function getCustomMedal($dv = NULL, $medalId = NULL)
    {
        $result = array('dataDv' => '0.0.1', 'newMedal' => array());

        if($medalId)
        {
            $medalId = intval($medalId);
            $newMedal = $this->getMedalInfo($medalId);

            $result['newMedal'][] = $newMedal;
        }
        else
        {
            $result['newMedal'] = $this->getCustomMedalList();
        }

        return $result;
    }

    /**
     * 获取所有自定义勋章信息
     * @return array
     */
    public function getCustomMedalList()
    {
        return $this->db->getAll('select * from r_medal where isCustom = 1');
    }

    /**
     * 获取用户的跑步勋章
     * @return array
     */
    public function getUserMedals($uid)
    {
        $medals = array();
        if($this->base->vn <= 1700 || ($this->base->vn < 1900 && $this->base->projectId == 1))
        {
            $data = $this->db->getAll("select medal_id, add_time from r_medal_record where uid = '{$uid}' and (medal_id<124 or medal_id >129) order by add_time DESC");
            if($data)
            {
                foreach ($data as $key => $value) {
                    $medalInfo = $this->getMedalInfo($value['medal_id']);
                    $value['number'] = 1;
                    $medals[] = array_merge($value,$medalInfo);
                    $this->redis->hset(REDIS_PREFIX.'UserMedal_'.$uid, $value['medal_id'], $value['number']);
                }
                unset($data);
            }
        }
        else
        {
            $data = $this->db->getAll("select medal_id, count(*) as number,add_time from r_medal_record where uid = '{$uid}' and (medal_id<124 or medal_id >133 or medal_id=130) group by medal_id order by record_id desc");
            if($data)
            {
                foreach ($data as $key => $value) {
                    $medalInfo = $this->getMedalInfo($value['medal_id']);
                    $medals[] = array_merge($value,$medalInfo);
                    $this->redis->hset(REDIS_PREFIX.'UserMedal_'.$uid, $value['medal_id'], $value['number']);
                }
                unset($data);
            }
        }
        $userInfo = $this->base->load('client')->getUserInfo($uid);
        $runRecords = array();
        $runRecords['farthest_record'] = $this->db->getRow("select mileage as value, updatetime from r_data where uid='{$uid}' and mileage > 0 and is_delete = 0 and overSpeed = 0 order by mileage DESC limit 1");
        $runRecords['longest_record'] = $this->db->getRow("select elapsedtime as value, updatetime from r_data where uid='{$uid}' and elapsedtime > 0 and is_delete = 0 and overSpeed = 0 and updatetime >= 1398434624 order by elapsedtime DESC limit 1");//跑步提交时间大于等于第一条的时间
        $runRecords['best_five'] = $this->db->getRow("select five_time as value, updatetime from r_data where uid='{$uid}' and five_time > 930 and is_delete = 0 and overSpeed = 0 order by five_time ASC limit 1");//按照每公里3分10秒速度计算
        $runRecords['best_ten'] = $this->db->getRow("select ten_time as value, updatetime from r_data where uid='{$uid}' and ten_time > 1900 and is_delete = 0 and overSpeed = 0 order by ten_time ASC limit 1");//按照每公里3分10秒速度计算
        $runRecords['best_halfm'] = $this->db->getRow("select half_mtime as value, updatetime from r_data where uid='{$uid}' and half_mtime > 4200 and is_delete = 0 and overSpeed = 0 order by half_mtime ASC limit 1");//按照1小时10分钟计算
        $runRecords['best_mara'] = $this->db->getRow("select mara_time as value, updatetime from r_data where uid='{$uid}' and mara_time > 8100 and is_delete = 0 and overSpeed = 0 order by mara_time ASC limit 1");//按照2小时15分钟计算
        $runRecords['max_speed'] = $this->db->getRow("select speed as value, updatetime from r_data where uid='{$uid}' and is_delete = 0 and overSpeed = 0 order by speed DESC limit 1");
        foreach ($runRecords as & $value)
        {
            if(empty($value))
            {
                $value = array('date' => '', 'value' => '');
            }
            else
            {
                $value['date'] = date("Y-m-d", $value['updatetime']);
                unset($value['updatetime']);
            }
        }
        $max_month_mileage = isset($userInfo['max_month_mileage']) ? $userInfo['max_month_mileage'] : 0;
        $updatetime = $max_month_mileage ? $this->db->getOne("select add_time from r_medal_record where uid={$uid} and medal_id=132") : 0;
        if($max_month_mileage && $updatetime){
            $runRecords['max_month_mileage'] = [];
            $runRecords['max_month_mileage']['value'] = $userInfo['max_month_mileage'];
            $runRecords['max_month_mileage']['date'] = $updatetime ? date('Y-m-d',$updatetime) : '';
        }
        
        $max_run_days = isset($userInfo['max_run_days']) ? $userInfo['max_run_days'] : 0;
        $updatetime = $max_run_days ? $this->db->getOne("select add_time from r_medal_record where uid={$uid} and medal_id=133") : 0;
        if($max_run_days && $updatetime){
            $runRecords['max_run_days'] = [];
            $runRecords['max_run_days']['value'] = $userInfo['max_run_days'];
            $runRecords['max_run_days']['date'] = $updatetime ? date('Y-m-d',$updatetime) : '';
        }
        
        $tmp_run_days = isset($userInfo['tmp_run_days']) ? $userInfo['tmp_run_days'] : 0;
        if($tmp_run_days && isset($userInfo['latestRunRecord']['run_time'])){
            $runRecords['tmp_run_days'] = [
                'value' => $tmp_run_days,
                'date' => $userInfo['latestRunRecord']['run_time']
            ];
        }

        return compact('medals','runRecords');
    }
    /**
     * 获取勋章判断依据相关数据
     * @return array
     */
    public function getMedalBasisData($uid)
    {
        $birthMedal = $this->db->getOne("select medal_id from r_medal where isCustom=2 order by medal_id desc limit 1");
        $birthMedal = $birthMedal ? $birthMedal : 121;
        
        $isGetFirstRun = $this->checkCanGetMedal($uid,100) ? 100 : 1;       // 跑步新星
        $isGetTargetRUn = $this->checkCanGetMedal($uid,101) ? 101 : 1;      // 决心
        $isGetDoubleRun = $this->checkCanGetMedal($uid,102) ? 102 : 1;      // Double Run
        $isGetBirthRun = $this->checkCanGetMedal($uid,$birthMedal) ? $birthMedal : 1;       // 生日祝福
        $isGetChirisRun = $this->checkCanGetMedal($uid,122) ? 122 : 1;      // 灿烂烟花
        $isGetNightRun = $this->checkCanGetMedal($uid,123) ? 123 : 1;       // 夜色浪漫
        $isGetCityRun = $this->checkCanGetMedal($uid,1032) ? 1032 : 1;      // 城市勋章
        $isGetFiftyRun = $this->checkCanGetMedal($uid, 130) ? 130 : 1;      // 跑霸

        $today = strtotime(date("Y-m-d"));
        $thisTime = time();
        $thisMonday = strtotime("next monday") - 7*86400;

        $runRateToday = $this->db->getOne("select count(*) from r_data where uid = '{$uid}' and is_delete = 0 and overSpeed = 0 and updatetime >= '{$today}' and updatetime < '{$thisTime}'");    // 今天跑步次数
        $runDaysWeek = $this->db->getCol("select distinct(FROM_UNIXTIME(updatetime,'%w')) from r_data where uid = '{$uid}'and is_delete = 0 and overSpeed = 0 and  updatetime>= '{$thisMonday}' and updatetime < '{$thisTime}'"); // 本周跑步天数

        $runInfoToday = array('date' => date("Y-m-d"), 'times' => $runRateToday);
        $runThisWeek = array('date' => date("Y-W"), 'days' => $runDaysWeek);
        
        return compact('isGetFirstRun', 'isGetTargetRUn','isGetDoubleRun', 'isGetBirthRun',
                    'isGetChirisRun', 'isGetNightRun', 'isGetAnnRun', 'runInfoToday',
                    'runThisWeek', 'isGetCityRun', 'isGetFiftyRun');
    }
    /**
     * 获取勋章判断依据相关数据（旧版）
     * @return array
     */
    public function getMedalBasisDataOld($uid)
    {
        $isGetFirstRun = $this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 100) ? 1 : 0;       // 跑步新星
        $isGetTargetRUn = $this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 101) ? 1:0;      // 决心
        $isGetDoubleRun = $this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 102) ? 1 : 0;   // Double Run
        $isGetBirthRun = $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_121', date("Y")) ? 1 : 0;   // 生日祝福
        $isGetChirisRun = $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_122', date("Y")) ? 1 : 0;   // 灿烂烟花
        $isGetNightRun = $this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 123) ? 1 : 0;   // 夜色浪漫
        //$isGetAnnRun = $this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, 120) ? 1 : 0;   // 周年纪念
        $isGetAnnRun = 1;

        $today = strtotime(date("Y-m-d"));
        $thisTime = time();
        $thisMonday = strtotime("next monday") - 7*86400;

        $runRateToday = $this->db->getOne("select count(*) from r_data where uid = '{$uid}' and is_delete = 0 and overSpeed = 0 and updatetime >= '{$today}' and updatetime < '{$thisTime}'");    // 今天跑步次数
        $runDaysWeek = $this->db->getCol("select distinct(FROM_UNIXTIME(updatetime,'%w')) from r_data where uid = '{$uid}'and is_delete = 0 and overSpeed = 0 and  updatetime>= '{$thisMonday}' and updatetime < '{$thisTime}'"); // 本周跑步天数

        $runInfoToday = array('date' => date("Y-m-d"), 'times' => $runRateToday);
        $runThisWeek = array('date' => date("Y-W"), 'days' => $runDaysWeek);
        return compact('isGetFirstRun', 'isGetTargetRUn','isGetDoubleRun', 'isGetBirthRun', 'isGetChirisRun', 'isGetNightRun', 'isGetAnnRun', 'runInfoToday', 'runThisWeek');
    }
    /**
     * 获取跑步记录新增勋章
     * @return array
     */
    public function getNewRecordMedal($uid)
    {
        $medalIds= array();
        $medals = array();
        if(empty($uid))
        {
            return array();
        }

        $start = strtotime("2014-09"); //从九月开始计时
        $deadLine = strtotime(date("Y-m"));
        $thisYearMon = date("Ym");
        $userInfo = $this->base->load('client')->getUserInfo($uid);
        // 连续跑步N个月 勋章
        $consisMedal = 0;
        $sql = "select FROM_UNIXTIME(updatetime,'%Y%m') as m, count(*) as times from r_data
                where uid = '{$uid}' and overSpeed = 0 and updatetime >= '{$start}' group by m order by m desc";
        $consisData = $this->db->getAll($sql);

        $isGive = $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_108', $thisYearMon) + $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_109', $thisYearMon) +
                  $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_110', $thisYearMon) + $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_111', $thisYearMon);
        if($consisData && !$isGive) // 如果本月未得过 "连续跑步N月" 的勋章， 发放勋章
        {
            $firstDate = $consisData[0]['m'];
            $firstTimes = $consisData[0]['times'];
            // 上个月是否得过 "连续跑步N月" 的勋章
            $isGiveLastMonth = $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_108', date("Ym",strtotime("first day of last month"))) + $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_109', date("Ym",strtotime("first day of last month"))) +
                  $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_110', date("Ym",strtotime("first day of last month"))) + $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_111', date("Ym",strtotime("first day of last month")));
            $consisMonth = 0; //连续跑步月数
            if($firstDate == date("Ym")|| ($firstDate == date("Ym", strtotime("first day of last month")) && $firstTimes >= 4 && !$isGiveLastMonth))
            {
                foreach ($consisData as $key => $value) {
                    if($key == 0 && $value['times'] >= 4)
                    {
                        $consisMonth +=1;
                    }
                    elseif($value['times'] >= 4 && (($consisData[$key-1]['m'] - $value['m']) == 1 || ($consisData[$key-1]['m'] - $value['m']) == 89))
                    {
                        $consisMonth +=1;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            switch ($consisMonth) {
                case 3:
                    $consisMedal = 108;
                    break;
                case 6:
                    $consisMedal = 109;
                    break;
                case 9:
                    $consisMedal = 110;
                    break;
                case 12:
                    $consisMedal = 111;
                    break;
                default:
                    # code...
                    break;
            }
            if($consisMedal)
            {
                $this->addUserMedal($uid, $consisMedal, $thisYearMon);
                $medalIds[] = $consisMedal;
            }
        }

        // 健康跑者 勋章
        $lastMonth = strtotime("midnight first day of last month");
        $sql = "select FROM_UNIXTIME(updatetime,'%Y%m') as m, sum(mileage) as mileage from r_data
                where uid = '{$uid}' and overSpeed = 0 and updatetime >= '{$lastMonth}' and updatetime < '{$deadLine}' group by m order by m desc limit 1";
        $lastMonthMil = $this->db->getRow($sql);
        $isGive = $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_112', $thisYearMon) + $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_113', $thisYearMon) +
                  $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_114', $thisYearMon) + $this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_115', $thisYearMon);
        if($lastMonthMil && !$isGive)
        {
            if($lastMonthMil['mileage'] > 100)
            {
                $mil_medal_id = 115;
            }
            elseif ($lastMonthMil['mileage'] > 80) {
                $mil_medal_id = 114;
            }
            elseif ($lastMonthMil['mileage'] > 40) {
                $mil_medal_id = 113;
            }
            elseif ($lastMonthMil['mileage'] > 20) {
                $mil_medal_id = 112;
            }
            if(isset($mil_medal_id))
            {
                $medalIds[] = $mil_medal_id;
                $this->addUserMedal($uid, $mil_medal_id, $thisYearMon);
            }
        }
        
        //最大月跑量
        $max_month_mileage = isset($userInfo['max_month_mileage']) ? $userInfo['max_month_mileage'] : 0;
        if($lastMonthMil['mileage'] && $this->checkCanGetMedal($uid,132) && $lastMonthMil['mileage'] > $max_month_mileage){
            $this->base->load('user')->setUserExt($uid, ['max_month_mileage'=>$lastMonthMil['mileage']]);
            $medalIds[] = 132;
            $this->addUserMedal($uid, 132, $thisYearMon);
        }
        
        //更新最长跑步天数
        $max_run_days = isset($userInfo['max_run_days']) ? $userInfo['max_run_days'] : 0;
        $tmp_run_days = isset($userInfo['tmp_run_days']) ? $userInfo['tmp_run_days'] : 0;
        if($tmp_run_days > $max_run_days){
            $this->base->load('user')->setUserExt($uid, ['max_run_days'=>$tmp_run_days]);
            //$medalIds[] = 133;
            $this->addUserMedal($uid, 133, date('Ymd'));
        }
        
        if($this->base->vn < 1900 && $this->base->projectId == 1)
        {
            return $medalIds;
        }
        if($medalIds)
        {
            foreach ($medalIds as $key => $medal_id) {
                $info = $this->getMedalInfo($medal_id);
                $medalInfo = array();
                $medalInfo['medal_id'] = $medal_id;
                $medalInfo['number'] = 1;
                $medalInfo['add_time'] = time();
                $medalInfo['isCustom'] = $info['isCustom'];
                $medalInfo['medal_name'] = $info['medal_name'];
                $medalInfo['word'] = $info['word'];
                $medalInfo['img1'] = $info['img1'];
                $medalInfo['img2'] = $info['img2'];
                $medalInfo['cate'] = $info['cate'];
                $medals[] = $medalInfo;
            }
        }
        return $medals;
    }
    /**
     * 用户新增加一个勋章
     * @return
     */
    public function addUserMedal($uid, $medal_id, $source_data)
    {
        $rel = false;
        $medal_id = intval($medal_id);
        $insert = array('uid'       => $uid,
                        'medal_id'  => $medal_id,
                        'add_time'  => time(),
                        'source_data'  => $source_data,
                        );
        $medalInfo = $this->getMedalInfo($medal_id);
        if($medalInfo)
        {
            $nowNumber = $this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, $medal_id);
            if(in_array($medal_id, array(124, 125, 126, 127, 128, 129, 131, 132, 133)) && $nowNumber) // 记录型，更新
            {
                $rel = $this->db->update("update r_medal_record set add_time = '".$insert['add_time']."', source_data = '{$source_data}' where uid = '{$uid}' and medal_id = '{$medal_id}'");
            }
            else
            {
                $insert['isCustom'] = $medalInfo['isCustom'];
                $rel = $this->db->insertRowTable('r_medal_record', $insert);
            }
            if($rel)
            {
                // 用户相应勋章获得数+1
                if(!in_array($medal_id, array(124, 125, 126, 127, 128, 129, 131, 132, 133)) || $nowNumber)
                {
                    $this->redis->hset(REDIS_PREFIX.'UserMedal_'.$uid, $medal_id, $nowNumber+1);
                }
                else
                {
                    $this->redis->hset(REDIS_PREFIX.'UserMedal_'.$uid, $medal_id, 1);
                }
                // 保存记录
                if($medalInfo['limit'] > 0 && $medalInfo['limit'] < 5)
                {
                    $this->redis->sadd(REDIS_PREFIX.'UserMedalEle_'.$uid.'_'.$medal_id, $source_data);
                }
                elseif($medalInfo['limit'] == 5)
                {
                    $this->redis->sadd(REDIS_PREFIX.'uniqueMedal_'.$medal_id, $uid);
                }
            }
        }
        return $rel;
    }
    /*
     * 剔除重复勋章
     */
    public function  verifyRunMedal($uid, $thisMedal, $updatetime)
    {
        $validMedal = array();
        $thisMedal = json_decode($thisMedal, true);
        if(is_array($thisMedal))
        {
            foreach ($thisMedal as $medal_id) {
                if($this->checkCanGetMedal($uid,$medal_id,$updatetime)){
                    $this->addUserMedal($uid, $medal_id, $updatetime);
                    $validMedal[] = $medal_id;
                }
            }
        }
        return json_encode($validMedal);
    }
    /*
     *  获取指定用户最近获取的勋章
    */
    public function  getLatestMedals($uid, $limit = 3)
    {
        $result = array();
        if(empty($uid)) return $result;
        $result = $this->db->getAll("select distinct(medal_id) as medal_id from r_medal_record where uid = '{$uid}' and (medal_id >'133' or medal_id < '124' or medal_id=130) order by add_time DESC limit $limit");
        if($result)
        {
            foreach ($result as & $value) {
                $medal_id = $value['medal_id'];
                $medalInfo = $this->getMedalInfo($medal_id);
                $value['medal_name'] = $medalInfo['medal_name'];
                $value['word'] = $medalInfo['word'];
                $value['isCustom'] = $medalInfo['isCustom'];
            }
        }
        return $result;
    }
    
    /*
     * 获取个人勋章总数
     */
    public function getMedalCount($uid){
        return $this->db->getOne("select count(*) from r_medal_record where uid=$uid");
    }
    
    /*
     * 获得所有勋章
     */
    public function getMedals($updatetime=null,$cate=null){
        $sql = "select * from r_medal where 1";
        if($updatetime){
            $sql .= " and updatetime>{$updatetime}";
        }
        if(is_numeric($cate)){
            $sql .= " and cate=$cate";
        }
        $sql .= " order by medal_id desc";
        return $this->db->getAll($sql);
    }
    
    /*
     * 插入
     */
    public function insert($data){
        $now = time();
        $data['addtime'] = $now;
        $data['updatetime'] = $now;
        $medal_id = $this->db->insertRowTable('r_medal',$data);
        if($medal_id){
            if(in_array($data['isCustom'],[1,3])){
                $this->redis->sadd(REDIS_PREFIX.'CMedalList',$medal_id);
            }else{
                $this->redis->sadd(REDIS_PREFIX.'SMedalList',$medal_id);
            }
        }
        return true;
    }
    
    /*
     * 更新
     */
    public function update($data){
        $data['updatetime'] = time();
        $res = $this->db->updateRowTable('r_medal',$data);
        $medal_id = $data['medal_id'];
        if($res && $medal_id){
            $this->redis->del(REDIS_PREFIX.'CMedalInfo_'.$medal_id);
            $this->redis->del(REDIS_PREFIX.'SMedalInfo_'.$medal_id);
            $this->redis->srem(REDIS_PREFIX.'CMedalList',$medal_id);
            $this->redis->srem(REDIS_PREFIX.'SMedalList',$medal_id);
            if(in_array($data['isCustom'],[1,3])){
                $this->redis->sadd(REDIS_PREFIX.'CMedalList', $medal_id);
            }else{
                $this->redis->sadd(REDIS_PREFIX.'SMedalList', $medal_id);
            }
        }
        return $res;
    }
    
    /*
     * 检测用户是否已经获得勋章
     */
    public function checkCanGetMedal($uid,$medal_id,$updatetime=null){
        $res = false;
        $medalInfo = $this->getMedalInfo($medal_id);
        if(empty($medalInfo)){
            return $res;
        }
        if($medalInfo['isCustom']==0 || $medalInfo['isCustom']==2){
            if(empty($updatetime)){
                $updatetime = time();
            }
            switch ($medalInfo['limit']) {
                case '0':
                    $res = $medal_id;
                    break;
                case '1':
                    if(!$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_'.$medal_id, date("Ymd", $updatetime)))
                    {
                        $res = $medal_id;
                    }
                    break;
                case '2':
                    if(!$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_'.$medal_id, date("YW", $updatetime)))
                    {
                        $res = $medal_id;
                    }
                    break;
                case '3':
                    if(!$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_'.$medal_id, date("Ym", $updatetime)))
                    {
                        $res = $medal_id;
                    }
                    break;
                case '4':
                    //121 生日祝福
                    //122 灿烂烟花
                    if(!$this->redis->sismember(REDIS_PREFIX.'UserMedalEle_'.$uid.'_'.$medal_id, date("Y", $updatetime)))
                    {
                        $res = $medal_id;
                    }
                    break;
                case '5':
                    /* 100 跑步新星
                     * 101 决心
                     * 102 Double Run
                     * 120 周年纪念
                     * 123 夜色浪漫
                     */
                    if(!$this->redis->sismember(REDIS_PREFIX.'uniqueMedal_'.$medal_id, $uid))
                    {
                        $res = $medal_id;
                    }
                    break;
                default:
                    # code...
                    break;
            }
        }elseif($medalInfo['isCustom']==4){
            $res = $medal_id;
        }elseif(!$this->redis->hget(REDIS_PREFIX.'UserMedal_'.$uid, $medal_id)){
            $res = $medal_id;
        }
        
        return $res;
    }
    
    /*
     * 通过tag添加勋章
     */
    public function addMedalByTag($uid,$tag){
        $tags = [
            'post' => [
                'count'=>20,
                'medal_id'=>1025,
                'sql' => "select count(*) from r_news where uid=$uid and is_show=1"
            ],
            'paidEnergy' => [
                'count'=>5000,
                'medal_id'=>1026,
                'sql'=> "select sum(energy_add) from r_energy_record where target_uid=$uid and (`type`='paid' or `type`='paomePaid')"
            ],
            'payEnergy' => [
                'count'=>5000,
                'medal_id'=>1027,
                'sql'=> "select sum(energy_add) from r_energy_record where uid=$uid and (`type`='pay' or `type`='paomePay')"
            ],
            'likePost' => [
                'count'=>500,
                'medal_id'=>1028,
                'sql' => "select count(*) from r_news_likes where uid=$uid and is_delete=0"
            ],
            'likedPost' => [
                'count'=>500,
                'medal_id'=>1029,
                'sql' => "select count(*) from r_news_likes left join r_news on r_news_likes.news_id=r_news.news_id where r_news_likes.is_delete=0 and r_news.uid=$uid"
            ]
        ];
        if(!array_key_exists($tag,$tags)){
            return false;
        }
        $medalRule = $tags[$tag];
        $medal_id = $medalRule['medal_id'];
        $res = $this->checkCanGetMedal($uid, $medal_id);
        if(!$res){
            return false;
        }
        $count = $this->db->getOne($medalRule['sql']);
        if(abs($count) < $medalRule['count']){
            return false;
        }
        $this->addUserMedal($uid, $medal_id, date('Ymd'));
        return $medal_id;
    }
}
?>
